package com.cqjtu.eecs.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqjtu.eecs.entity.Major;
import com.cqjtu.eecs.entity.Student;
import com.cqjtu.eecs.entity.Teacher;
import com.cqjtu.eecs.entity.User;
import com.cqjtu.eecs.entity.dto.CurrUserInfo;
import com.cqjtu.eecs.entity.params.user.UserParams;
import com.cqjtu.eecs.entity.vo.UserVO;
import com.cqjtu.eecs.exception.NotFoundException;
import com.cqjtu.eecs.exception.ParamsErrorException;
import com.cqjtu.eecs.service.*;
import com.cqjtu.eecs.utils.Assert;
import com.cqjtu.eecs.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.security.Principal;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author luojun
 * @since 2022-03-04
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理接口")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IMajorService majorService;
    @Autowired
    private ITeacherService teacherService;


    @ApiOperation("添加用户")
    @PostMapping("/add")
    public Result addUser(@Valid @RequestBody UserParams userParams) {
        Assert.notNull(userParams.getRoleNames(), new ParamsErrorException("用户角色不能为空"));
        if (userService.saveUser(userParams))
            return Result.success();
        return Result.error();
    }

    @ApiOperation("分页获取用户信息")
    @GetMapping("/listUserPage/{page}/{size}")
    public UserVO listUserPage(@PathVariable("page") Long page, @PathVariable("size") Long size) {
        Assert.notNull(page, new ParamsErrorException("The page cannot be null"));
        Assert.notNull(size, new ParamsErrorException("The size cannot be null"));
        return userService.listUserByPage(page, size);
    }

    @ApiOperation("分页用户名模糊查询")
    @GetMapping("/listUserPageByName/{page}/{size}/{name}")
    public UserVO listUserPageByName(
            @PathVariable("page") Long page,
            @PathVariable("size") Long size,
            @PathVariable("name") String name
    ) {
        Assert.notNull(page, new ParamsErrorException("The page cannot be null"));
        Assert.notNull(size, new ParamsErrorException("The size cannot be null"));
        Assert.notBlank(name, new ParamsErrorException("The size cannot be null or blank"));
        return userService.listUserPageByName(page, size, name);
    }

    @ApiOperation("通过用户名获取用户的角色")
    @GetMapping("/listRoleByName/{name}")
    public List<String> listRoleByName(@PathVariable("name") String name) {
        Assert.notBlank(name, new ParamsErrorException("The size cannot be null or blank"));
        return userService.listRoleByName(name);
    }

    @ApiOperation("修改用户的角色")
    @PutMapping("/updateUserRole/{name}")
    public Result updateUserRole(@PathVariable("name") String name, @RequestBody List<String> roles) {
        Assert.notBlank(name, new ParamsErrorException("The name cannot be null"));
        Assert.notNull(roles, new ParamsErrorException("The roles cannot be null"));
        if (userService.updateUserRole(name, roles))
            return Result.success();
        return Result.error();
    }

    @ApiOperation("通过用户名删除用户")
    @DeleteMapping("/deleteByName/{name}")
    public Result deleteByName(@PathVariable("name") String name) {
        Assert.notBlank(name, new ParamsErrorException("The name cannot be null or blank"));
        if (userService.remove(new LambdaQueryWrapper<User>().eq(User::getUsername, name)))
            return Result.success();
        return Result.error(-1, "不存在该用户");
    }

    @PreAuthorize("hasAnyRole('major_manger')")
    @ApiOperation("获取当前登录用户的专业代码")
    @GetMapping("/getUserMajorCode")
    public String getLoginUserInfo(Principal principal) {
        String name = principal.getName();
        User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, name));
        Assert.notNull(one, new NotFoundException("Not find the user"));
        // 教职工中查找
        Teacher teacher =
                teacherService
                        .getOne(new LambdaQueryWrapper<Teacher>()
                                .eq(Teacher::getTeacherCode, one.getUsername()));
        Assert.notNull(teacher, new NotFoundException("Not find the student"));
        // 在major中获取
        Major major = majorService.getOne(new LambdaQueryWrapper<Major>().eq(Major::getTid, teacher.getTid()));
        return major.getMajorCode();
    }


    @GetMapping("/curr-user-info")
    @ApiOperation(value = "获取当前登录用户信息")
    public CurrUserInfo getCurrentUserInfo(Principal principal) {
        if (principal == null)
            return null;
        return userService.getCurrentUserInfo(principal.getName());
    }

}
